from twisted.internet import reactor
from websocket import WebSocketHandler, WebSocketSite
from twisted.web.static import File
import json;
from core import ProtocalPool
from messages import ProtocalTypes,CSAddMessage,CSSubMessage,CSMulMessage,CSDivMessage
from handlers import AddHandler,SubHandler,MulHandler,DivHandler

class Dinnerhandler(WebSocketHandler):
    
    protocalPool = ProtocalPool()
    protocalPool.register(ProtocalTypes.CS_ADD,CSAddMessage,AddHandler())
    protocalPool.register(ProtocalTypes.CS_SUB,CSSubMessage,SubHandler())
    protocalPool.register(ProtocalTypes.CS_MUL,CSMulMessage,MulHandler())
    protocalPool.register(ProtocalTypes.CS_DIV,CSDivMessage,DivHandler())
    
    def __init(self):
        WebSocketHandler.__init__(self);

    def frameReceived(self, frame):
        print frame;
        msg = json.loads(frame,encoding="utf-8");
        if(not msg or not msg['type']) :
            return;
        protocal = Dinnerhandler.protocalPool.getProtocal(msg['type'])
        protocal.read(msg['data']);
        handler = Dinnerhandler.protocalPool.getHandler(msg['type'])
        result = handler.process(protocal)
        if(result):
            self.transport.write(result);

    def connectionMade(self):
        pass

    def connectionLost(self, reason):
        pass

if __name__ == "__main__":
    # run our websocket server
    # serve index.html from the local directory
    root = File('.')
    site = WebSocketSite(root)
    site.addHandler('/dinner', Dinnerhandler)
    reactor.listenTCP(8001, site)
    reactor.run()